<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

const chartRef = ref(null);

// 格式化时间戳为 YYYY-MM-DD HH:mm 的形式
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

onMounted(() => {
  const chart = echarts.init(chartRef.value);

  const fetchDataAndUpdateChart = async () => {
    try {
      const response = await axios.get('http://localhost:8085/SoilWater/tenSoilWaterdata');
      const data = response.data;

      const timeData = data.map(item => formatDateTime(item.createTime));
      const soilMoistureData = data.map(item => item.dataValue);


      const option = {
        title: {
          text: '土壤含水率随时间变化',
          left: 'center',
          textStyle: { color: '#FFFFFF' },
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            const time = params[0].name;
            const soilMoisture = params[0].data;
            return `${time}<br>土壤含水率: ${soilMoisture}%`;
          },
        },
        // legend: {
        //   data: ['土壤含水率'],
        //   textStyle: { color: '#FFFFFF' },
        //   top: '10%',
        // },
        xAxis: {
          type: 'category',
          data: timeData,
          axisLabel: { rotate: 45, color: '#FFFFFF' },
          axisLine: { lineStyle: { color: '#FFFFFF' } },
          axisTick: { show: true, lineStyle: { color: '#FFFFFF' } },
        },
        yAxis: {
          type: 'value',
          name: '含水率 (%)',
          axisLabel: { color: '#FFFFFF' },
          axisLine: { lineStyle: { color: '#FFFFFF' } },
          axisTick: { show: true, lineStyle: { color: '#FFFFFF' } },
        },
        series: [
          {
            name: '土壤含水率',
            type: 'bar',
            data: soilMoistureData,
            itemStyle: { color: '#0000FF' },
            barWidth: '50%',
          },
        ],
        grid: { left: '10%', right: '10%', bottom: '10%', top: '20%' },
        dataZoom: [{ type: 'inside', start: 0, end: 100 }],
      };

      chart.setOption(option);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  };

  fetchDataAndUpdateChart();
  setInterval(fetchDataAndUpdateChart, 300000); // 每5分钟更新一次数据
});
</script>

<template>
  <dv-border-box10>
    <div ref="chartRef" style="width: 430px; height: 210px;margin-left: 20px;margin-top: 10px"></div>
  </dv-border-box10>
</template>

<style scoped>

</style>